<template>
  <div id="menuConfigCustomeruration">
    <el-card class="box-card">
      <!-- 头部 -->
      <template #header>
        <div class="card-header">
          <span>机构列表</span>
        </div>
      </template>
      <!-- 按钮组 -->
      <el-row class="row-bg" justify="space-between">
        <el-col :span="12">
          <el-form-item class="el-form-item">
            <el-button
              type="primary"
              class="height40"
              @click="onClickAddCustomer"
              >新增机构</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 表格 -->
      <el-table
        :data="tableData"
        style="width: 100%; margin-bottom: 20px"
        border
      >
        <el-table-column prop="id" label="编号" width="60" />
        <el-table-column prop="name" label="名称" width="100" />
        <!-- <el-table-column
          prop="main_application_name"
          label="主应用"
          width="170"
        /> -->
        <el-table-column label="主应用" width="220">
          <template #default="scope">
            <div
              class="mainApplication"
              @click="mainApplication(scope.row.appIds)"
              v-for="item in scope.row.main_application_name"
            >
              {{ item }}
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="mobile" label="电话" width="120" />
        <el-table-column prop="expiredate" label="状态" width="90">
          <template #default="scope">
            <div class="status">
              <div class="status_item">
                <div v-if="scope.row.status == '1'">运行中</div>
                <div v-else-if="scope.row.status == '2'">过期</div>
                <div v-else-if="scope.row.status == '3'">停用</div>
                <div v-else>未知</div>
              </div>
              <div class="date">
                {{ scope.row.expiredate }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="defaultPid" label="开通省份" width="120">
          <template #default="scope">
            <div class="provinceLength">
              <span>
                <el-tooltip class="box-item" effect="dark" placement="bottom">
                  <template #content>
                    {{ selectCity(scope.row.pids) }}
                  </template>
                  <!-- {{ scope.row.pids.split(',').length }} -->
                  {{
                    scope.row.pids
                      ? scope.row.pids
                          .split(',')
                          .filter((pid) => pid.trim() !== '').length
                      : 0
                  }}
                </el-tooltip>
              </span>
              <span style="font-size: 12px">{{
                '(' + defalutCity(scope.row.defaultPid) + ')'
              }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="付款余额" width="100">
          <template #default="scope">
            <div style="text-align: center">
              {{ Number(scope.row.storeBalance || 0).toFixed(2) }}
            </div>
          </template>
        </el-table-column>

        <el-table-column label="提现余额" width="100">
          <template #default="scope">
            <div style="text-align: center">
              {{ Number(scope.row.balance || 0).toFixed(2) }}
            </div>
          </template>
        </el-table-column>

        <el-table-column label="基础配置" width="150">
          <!-- 域名配置 -->
          <template #default="scope">
            <div class="configuration">
              <div
                class="curr"
                style="color: dodgerblue"
                @click="onClickHostInfo(scope.row)"
              >
                域名配置
              </div>
              <div
                class="curr"
                style="color: dodgerblue"
                @click="availableMenu(scope.row)"
              >
                菜单配置
              </div>
            </div>
            <div class="configuration">
              <div
                class="curr"
                style="color: dodgerblue"
                @click="onClickwebsiteInfo(scope.row)"
              >
                网站配置
              </div>
              <div
                class="curr"
                style="color: dodgerblue"
                @click="handleAccountConfig(scope.row)"
              >
                账号配置
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="permissions" label="开关" width="140">
          <template #default="{ row }">
            <div class="flex switch">
              <div v-for="(item, index) in row.switches" :key="index">
                <el-switch
                  v-model="item.value"
                  inline-prompt
                  :active-text="item.activeText"
                  :inactive-text="item.inactiveText"
                  @change="handleSwitchChange(item, row, index)"
                  :loading="loadingStates[index]"
                />
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="date" label="操作" fixed="right">
          <template #default="scope">
            <div class="alitem">
              <div class="icon-button" @click="onClickChangeStatus(scope.row)">
                <el-icon size="16" style="cursor: pointer">
                  <SetUp />
                </el-icon>
                <span>{{ scope.row.status == '1' ? '停用' : '启用' }}</span>
              </div>

              <div class="icon-button" @click="onClickEditCustomer(scope.row)">
                <el-icon size="16" style="cursor: pointer">
                  <EditPen />
                </el-icon>
                <span>编辑</span>
              </div>

              <div class="icon-button" @click="onClickDeleteInfo(scope.row)">
                <el-icon size="16" style="cursor: pointer">
                  <Delete />
                </el-icon>
                <span>删除</span>
              </div>
              <div></div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="right" style="margin-top: 20px">
        <el-config-provider :locale="zhCn">
          <el-pagination
            v-model:current-page="pageData.page"
            v-model:page-size="pageData.pageSize"
            :page-sizes="[10, 20, 30]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageData.total ?? 0"
            @size-change="getCustomer"
            @current-change="getCustomer"
          />
        </el-config-provider>
      </div>
    </el-card>
  </div>
  <!-- 添加目录 -->
  <addCustomerDialog
    v-if="optionsDataList.length > 0"
    ref="addCustomerDialogRef"
    :optionsDataList="optionsDataList"
    :provinceList="provinceList"
    @getCustomer="getCustomer"
  />
  <!-- 添加菜单 -->
  <hostInfoDialog ref="hostInfoDialogRef" />
  <websiteInfoDialog ref="websiteInfoDialogRef" />
  <!-- 账号配置 -->
  <accountConfigDialog ref="accountConfigDialogRef"></accountConfigDialog>
</template>

<script setup>
import {
  delCustomer,
  getCustomerList,
  setStartOrEnd,
  getAppList,
  getProvinceInfo2,
} from '@/api/appv2/appv2';
import addCustomerDialog from './module/addCustomerDialog.vue';
import hostInfoDialog from './module/hostInfoDialog.vue';
import websiteInfoDialog from './module/websiteInfoDialog.vue';
import accountConfigDialog from './module/accountConfigDialog.vue';
import zhCn from 'element-plus/es/locale/lang/zh-cn';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
const router = useRouter();

import { reactive, ref, onMounted } from 'vue';
const { proxy } = getCurrentInstance();
const tableData = ref([]);
const addCustomerDialogRef = ref(null);
const hostInfoDialogRef = ref(null);
const websiteInfoDialogRef = ref(null);
const accountConfigDialogRef = ref(null);
// const defaultProvince = ref([]);
const optionsDataList = ref([]); //主运用列表
// api
import api from '@/modules'; // 默认配置项
const { saveConfigDataApi } = api;
const loadingStates = reactive({}); // 初始化loading状态管理对象
const provinceList = ref([]);
const pageData = ref({
  page: 1,
  pageSize: 10,
  total: 0,
});
const tableConfig = ref({
  page: 1,
  pageSize: 10,
});
// 获取菜单列表
function getCustomer() {
  getCustomerList(pageData.value).then((res) => {
    tableData.value = res.data.data;
    pageData.value = {
      page: res.data.current_page,
      pageSize: res.data.per_page,
      total: res.data.total,
    };
  });
}
getCustomer();

// 新增目录
function onClickAddCustomer() {
  addCustomerDialogRef.value.openchange();
}
// 点击查看域名信息
function onClickHostInfo(val) {
  hostInfoDialogRef.value.openchange(val);
}
// 可用菜单
function availableMenu(val) {
  router.push({ path: '/customer/availableMenu', query: { id: val.id } });
}
// 点击查看网站信息
function onClickwebsiteInfo(val) {
  websiteInfoDialogRef.value.openchange(val);
}
// 点击改变机构状态
function onClickChangeStatus(val) {
  let countent = '';
  if (val.status == '1') {
    countent = '是否停用 ' + val.name + ' ?';
  } else {
    countent = '是否启用 ' + val.name + ' ?';
  }
  proxy.$modal
    .confirm(countent)
    .then(function () {
      return setStartOrEnd({
        id: val.id,
        do: val.status == '1' ? 'off' : 'on',
      });
    })
    .then(() => {
      proxy.$modal.msgSuccess('修改成功');
      getCustomer();
    });
}
// 点击编辑机构
function onClickEditCustomer(val) {
  addCustomerDialogRef.value.openchange(val);
}
// 删除
function onClickDeleteInfo(val) {
  let countent = '是否删除该机构';

  proxy.$modal
    .confirm(countent)
    .then(function () {
      return delCustomer({
        id: val.id,
      });
    })
    .then((res) => {
      if (res.code === 20000) {
        proxy.$modal.msgSuccess('删除成功');
        getCustomer();
      }
    });
}
// 账号配置
const handleAccountConfig = (row) => {
  accountConfigDialogRef.value.openchange(row);
};
// 处理开关的切换事件
const handleSwitchChange = async (item, row, index) => {
  loadingStates[index] = true;
  const { value: data, storeId } = { ...item, ...row };
  const res = await saveConfigDataApi({
    storeId,
    configName: item.name,
    data: data ? 1 : 0,
  });
  if (res.code == 20000) {
    ElMessage.success('修改成功');
  }
  loadingStates[index] = false;
  getCustomer();
};
// 主运用跳转
const mainApplication = (item) => {
  console.log(item, 'item');
  router.push({ path: '/customer/permissionConfig', query: { id: item } });
};
// 添加应用
const getSelectAppList = async () => {
  const { data } = await getAppList(tableConfig.value);
  const res = data.data;
  optionsDataList.value = res;
};
// 获取省份
const provinceDataList = async () => {
  const { data } = await getProvinceInfo2({
    storeId: 1,
  });
  provinceList.value = data;
};
// 默认省份
const defalutCity = (val) => {
  if (provinceList.value.length) {
    const data = provinceList.value?.find((item) => item.id == val);
    return data?.provinceName ?? '';
  }
};
// 选中的省份
const selectCity = (val) => {
  if (provinceList.value.length) {
    const arr = val.split(',');
    // 使用 filter 获取匹配的对象
    const result = provinceList.value.filter((item) =>
      arr.includes(item.id.toString())
    );
    const city = result.map((item) => item.provinceName);
    return city.join(',');
  }
};
onMounted(() => {
  getSelectAppList();
  provinceDataList();
});
</script>

<style lang="scss" scoped>
.box-card {
  margin: 20px;

  .card-header {
    font-size: 20px;
    font-weight: 600;
    color: #1d2129;
    padding: 10px;

    .headerSize {
      color: #4e5969;
      font-size: 14px;
      margin-left: 12px;
      font-weight: 400;
      height: 20px;
      line-height: 21px;
    }
  }
}

.row-bg {
  .el-form-item {
    margin: 10px 0 20px;
  }
}

.alitem {
  .icon-button {
    display: flex;
    flex-direction: row;
    align-items: center;
    margin-right: 10px;
    /* 将光标设置为手型 */
    cursor: pointer;
  }
}
.switch {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}
.date {
  text-align: center;
  font-size: 8px;
  color: red;
}
.status_item {
  text-align: center;
}
.provinceLength {
  font-size: 20px;
  text-align: center;
}
.configuration {
  display: flex;
  justify-content: space-between;
}
.mainApplication {
  text-align: center;
  cursor: pointer;
}
</style>
